/*
 =============================================================================
 FILE...............: StorageService.java
 COMMENTS...........: Represents a storage service.
 =============================================================================
 AUTHOR(S)..........: Everton Ranielly de Sousa Cavalcante
 					  Department of Informatics and Applied Mathematics
 					  Federal University of Rio Grande do Norte
 LAST MODIFICATION..: November 26th, 2012
 ============================================================================= 					  
*/


/* ========================================================================= */
/* PACKAGES							                                         */
/* ------------------------------------------------------------------------- */
package services;


/* ========================================================================= */
/* IMPORTS							                                         */
/* ------------------------------------------------------------------------- */
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import model.Booking;
import model.Receipt;


/* ========================================================================= */
/* CLASS StorageService				                                         */
/* ------------------------------------------------------------------------- */
/**
 * Represents a storage service
 * @author Everton Cavalcante
 */
public class StorageService 
{
	/**
	 * Generates a receipt regarding the booking
	 * @param booking Booking
	 * @return A receipt regarding the booking
	 */
	public Receipt generateReceipt(Booking booking) 
	{
		// Generated receipt
		Receipt receipt = new Receipt();
				
		// Generates a random 12-digit receipt code
		char[] receiptChar = new char[12];
		for (int i = 0; i < 12; i++)
			receiptChar[i] = (char)(48 + (int)(9 * Math.random()));	// Random integer between 48 (0) and 57 (9)
		receipt.setCode(new String(receiptChar));
		receipt.setBooking(booking);
		
		// Generates a file regarding the receipt
		storeFile(receipt);
				
		return receipt;
	}
	
	
	/**
	 * Stores a file regarding the receipt
	 * @param receipt Receipt
	 */
	private void storeFile(Receipt receipt) 
	{
		try
		{
			// Creates a new file with the contents
			String filename = receipt.getCode() + ".txt";
			File f = new File(filename);
	        PrintWriter pw = new PrintWriter(f);
	        pw.write(receipt.toString());
	        pw.close();
		}
		catch (IOException ex)
		{ ex.printStackTrace(); }
	}
}
